<template>
  <div class="detail">
    <PageTitle title="商品详情"></PageTitle>
    <div class="skeleton" v-if="!detail">
      <div class="box"></div>
      <van-skeleton title :row="3" />
    </div>
    <div class="pageContent" v-if="detail">
      <van-tabs
        v-model="tabActive"
        scrollspy
        sticky
        offset-top="1.49rem"
        color="#25c9c3"
      >
        <van-tab title="商品">
          <van-swipe :autoplay="3000" indicator-color="white">
            <van-swipe-item
              v-for="(image, index) in detail.storeInfo.slider_image"
              :key="index"
            >
              <div class="img">
                <van-image lazy-load fit="cover" :src="image" />
              </div>
            </van-swipe-item>
          </van-swipe>
          <div class="info">
            <div class="top">
              <div class="left">
                <div class="price">
                  <span class="icon">￥</span>{{ detail.storeInfo.price }}
                </div>
                <div class="vip_price">
                  <span class="icon">￥</span>{{ detail.storeInfo.vip_price }}
                </div>
              </div>
              <div class="share" @click="showShare = true">
                <van-icon name="share-o"></van-icon>
              </div>
            </div>
            <div class="name">{{ detail.storeInfo.store_name }}</div>
            <div class="bottom">
              <div class="ot_price">
                原价：￥{{ detail.storeInfo.ot_price }}
              </div>
              <div class="stock">
                库存：{{ detail.storeInfo.stock
                }}{{ detail.storeInfo.unit_name }}
              </div>
              <div class="fsales">
                销量：{{ detail.storeInfo.fsales
                }}{{ detail.storeInfo.unit_name }}
              </div>
            </div>
          </div>
          <van-cell is-link class="cell cart_selected" @click="show = true">
            <template #title>
              <span class="">{{ skuData ? "已选择：" : "选择规格" }}</span>
              <span class="selected">{{ skuData }}</span>
            </template>
          </van-cell>
        </van-tab>
        <van-tab title="评价">
          <van-cell title="用户评价(0)" is-link class="cell evaluation">
            <template #right-icon>
              <div class="good">
                <span>0%</span>好评率<van-icon
                  name="arrow"
                  color="#969799"
                  class="van-cell__right-icon"
                />
              </div>
            </template>
          </van-cell>
        </van-tab>
        <van-tab title="详情">
          <div class="description">
            <van-divider>商品描述</van-divider>
            <div
              class="desInfo"
              v-html="detail.storeInfo.description || tempHTML"
            ></div>
          </div>
        </van-tab>
        <van-tab title="推荐">
          <div class="recommend">
            <van-divider>相关推荐</van-divider>
            <van-swipe :autoplay="0" indicator-color="#25c9c3">
              <van-swipe-item
                v-for="(item, index) in recomList"
                :key="'rec' + index"
              >
                <div class="recPage">
                  <div
                    v-for="info in item"
                    :key="info.id"
                    class="recItem"
                    @click="
                      $router.replace('/detail/' + info.id), $router.go(0)
                    "
                  >
                    <div class="img">
                      <img :src="info.image" />
                    </div>
                    <p class="title">{{ info.store_name }}</p>
                    <p class="price">￥{{ info.price }}</p>
                  </div>
                </div>
              </van-swipe-item>
            </van-swipe>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <div class="bottom">
      <van-goods-action>
        <van-goods-action-icon
          icon="cart-o"
          text="购物车"
          to="/cart"
          :badge="
            cartList && cartList.valid.length ? cartList.valid.length : ''
          "
        />
        <van-goods-action-icon
          :icon="detail && detail.storeInfo.userCollect ? 'star' : 'star-o'"
          :text="detail && detail.storeInfo.userCollect ? '已收藏' : '收藏'"
          :color="detail && detail.storeInfo.userCollect ? '#25c9c3' : ''"
          @click="
            detail && detail.storeInfo.userCollect ? delCollect() : addCollect()
          "
        />
        <van-goods-action-button
          type="warning"
          text="加入购物车"
          @click="show = true"
        />
        <van-goods-action-button
          type="danger"
          text="立即购买"
          @click="show = true"
        />
      </van-goods-action>
      <van-sku
        v-if="detail"
        v-model="show"
        :sku="sku"
        :goods="goods"
        :goods-id="detail.storeInfo.id"
        :message-config="messageConfig"
        @buy-clicked="onBuyClicked"
        @add-cart="onAddCartClicked"
        @sku-selected="skuClicked"
        ref="sku"
      />
    </div>
    <van-share-sheet
      v-model="showShare"
      title="立即分享给好友"
      :options="shareOptions"
      @select="onShareSelect"
    />
  </div>
</template>

<script>
import PageTitle from "@/components/PageTitle";
import { mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Detail",
  props: ["id"],
  components: { PageTitle },
  data() {
    return {
      tabActive: 0,
      detail: null,
      skuData: null,
      show: false,
      goods: {
        picture: null,
      },
      messageConfig: {
        // 数据结构见下方文档
      },
      tempHTML: `<h6 style="text-align:center;padding: 50px 0;color: #ccc">该商品暂无描述</h6>`,
      recomList: null,
      showShare: false,
      shareOptions: [
        [
          { name: "微信", icon: "wechat" },
          { name: "朋友圈", icon: "wechat-moments" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" },
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
          { name: "小程序码", icon: "weapp-qrcode" },
        ],
      ],
    };
  },
  computed: {
    ...mapGetters(["cartList"]),
    sku() {
      let de = this.detail;
      if (!de) return null;
      let sku = {};
      sku.price = de.storeInfo.price;
      sku.stock_num = de.storeInfo.stock;

      sku.tree = [];
      de.productAttr.map((item, index) => {
        let obj = {};
        obj.k = item.attr_name;
        obj.k_s = "s" + index;
        obj.v = [];
        item.attr_values.map((val) => {
          let vObj = {};
          vObj.name = vObj.id = val;
          obj.v.push(vObj);
        });
        sku.tree.push(obj);
      });

      sku.list = [];
      let keys = Object.keys(de.productValue);
      keys.map((key) => {
        let obj = {};
        let typeList = key.split(",");
        typeList.map((type, i) => {
          obj["s" + i] = type;
        });
        obj.id = de.productValue[key].unique;
        obj.price = parseFloat(de.productValue[key].price) * 100;
        obj.stock_num = de.productValue[key].stock;
        sku.list.push(obj);
      });
      // console.log("sku", sku);
      return sku;
    },
  },
  created() {
    this.changeLoading(true);
    this.getCartInfo();
    this.$axios.get(`api/product/detail/${this.id}`).then((d) => {
      console.log("detail", d.data);
      this.changeLoading(false);
      this.detail = d.data.data;
      this.goods.picture = this.detail.storeInfo.slider_image[0];

      let gd = this.detail.good_list;
      let arr = [];
      for (var i = 0; i < gd.length / 6; i++) {
        arr[i] = gd.slice(6 * i, 6 * (i + 1));
      }
      this.recomList = arr;
      // console.log(this.recomList);
    });
    document.onscroll = function () {
      let tab = document.getElementsByClassName("van-sticky")[0];
      if (!tab) return;
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      tab.style.opacity = Math.min(1, scrollTop / document.body.clientWidth);
    };
  },
  destroyed() {
    document.onscroll = null;
  },
  methods: {
    ...mapActions(["getCartInfo"]),
    ...mapMutations(["changeLoading"]),
    onBuyClicked(info) {
      if (!this.$store.getters.tokens) {
        this.$router.push("/login");
        return;
      }
      this.changeLoading(true);
      let opt = {
        cartNum: info.selectedNum,
        new: 1,
        productId: info.goodsId,
        uniqueId: info.selectedSkuComb ? info.selectedSkuComb.id : null,
      };
      this.$axios.post("/api/cart/add", opt).then((d) => {
        console.log("cart/add", d.data);
        this.changeLoading(false);
        this.show = false;
        if (d.data.status == 200) {
          let cartId = d.data.data.cartId;
          this.$router.push(`/order/confirm/${cartId}`);
        } else if (d.data.status == 400) {
          this.$toast.fail("后台数据错误");
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        }
      });
    },
    onAddCartClicked(info) {
      if (!this.$store.getters.tokens) {
        this.$router.push("/login");
        return;
      }
      this.changeLoading(true);
      let opt = {
        cartNum: info.selectedNum,
        new: 0,
        productId: info.goodsId,
        uniqueId: info.selectedSkuComb ? info.selectedSkuComb.id : null,
      };
      // console.log(opt);
      this.$axios.post("/api/cart/add", opt).then((d) => {
        console.log("cart/add", d.data);
        this.changeLoading(false);
        this.show = false;
        if (d.data.status == 200) {
          this.getCartInfo();
          this.$toast.success("添加成功");
        } else if (d.data.status == 400) {
          this.$toast.fail("后台数据错误");
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        }
      });
    },
    skuClicked({ selectedSku: sku }) {
      this.skuData = null;
      let arr = [];
      let key = Object.keys(sku);
      for (var k of key) {
        if (!sku[k]) return;
        arr.push(sku[k]);
      }
      let type = arr.join(",");
      // console.log(type);
      this.skuData = type;
      let info = this.detail.productValue[type];
      if (info) this.goods.picture = info.image;
    },
    addCollect() {
      if (!this.detail || this.collectFlag) return;
      if (!this.$store.getters.tokens) {
        this.$router.push("/login");
        return;
      }
      this.collectFlag = true;
      this.$axios
        .post("/api/collect/add", {
          category: "product",
          id: this.detail.storeInfo.id,
        })
        .then((d) => {
          console.log("collect/add", d.data);
          this.collectFlag = false;
          if (d.data.status == 200) {
            this.detail.storeInfo.userCollect = true;
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          }
        });
    },
    delCollect() {
      if (!this.detail || this.collectFlag) return;
      if (!this.$store.getters.tokens) {
        this.$router.push("/login");
        return;
      }
      this.collectFlag = true;
      this.$axios
        .post("/api/collect/del", {
          category: "product",
          id: this.detail.storeInfo.id,
        })
        .then((d) => {
          console.log("collect/del", d.data);
          this.collectFlag = false;
          if (d.data.status == 200) {
            this.detail.storeInfo.userCollect = false;
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          }
        });
    },
    onShareSelect(option) {
      this.$toast(option.name);
      this.showShare = false;
    },
  },
};
</script>
<style lang="less" scoped>
.detail {
  .pageTitle {
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    width: 100%;
  }
  .skeleton {
    margin-top: 56px;
    .box {
      width: 100%;
      padding-bottom: 100%;
      background: #f4f5f6;
    }
    .van-skeleton {
      margin-top: 15px;
    }
  }
  .pageContent {
    margin-top: 56px;
    margin-bottom: 69px;
    .van-tabs {
      ::v-deep.van-sticky {
        z-index: 9999;
        visibility: hidden;
        height: 0;
        .van-tabs__line {
          display: none;
        }
        &.van-sticky--fixed {
          visibility: unset;
          height: unset;
          .van-tabs__line {
            display: block;
          }
        }
      }
    }
    .van-swipe {
      width: 100%;
      .img {
        width: 100%;
        height: 0;
        padding-bottom: 100%;
        position: relative;
        .van-image {
          width: 100%;
          height: 100%;
          position: absolute;
        }
      }
    }
    .info {
      padding: 15px;
      background: #fff;
      .top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 3px;
        .left {
          display: flex;
          align-items: flex-end;
          line-height: 24px;
          vertical-align: bottom;
          .icon {
            font-size: 14px;
          }
          .price {
            font-size: 24px;
            font-weight: bold;
            color: #24c1bb;
          }
          .vip_price {
            color: #282828;
            font-size: 14px;
            font-weight: bold;
            margin-left: 5px;
            &::after {
              content: "VIP";
              line-height: 16px;
              padding: 2px 6px;
              transform: scale(0.6);
              transform-origin: left;
              display: inline-block;
              color: rgb(248, 226, 125);
              background-color: #282828;
              border-radius: 5px;
            }
          }
        }
        .share {
          display: flex;
          align-items: center;
          padding: 0 5px;
          &:active {
            background: #f2f3f5;
          }
          .van-icon {
            color: #82848f;
            font-size: 18px;
          }
        }
      }
      .name {
        font-size: 16px;
        font-weight: bold;
      }
      .bottom {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #82848f;
        margin-top: 12px;
      }
    }
    .cell.van-cell {
      margin: 15px 0;
      &.cart_selected {
        span {
          font-size: 14px;
          color: #82848f;
          &.selected {
            color: inherit;
          }
        }
      }
      &.evaluation {
        .good {
          color: #82848f;
          span {
            color: #24c1bb;
          }
          .van-icon {
            vertical-align: middle;
          }
        }
      }
    }
    .description {
      background: #fff;
      .van-divider {
        padding-top: 15px;
        color: inherit;
        font-size: 15px;
      }
      .desInfo {
        width: 100%;
        box-sizing: border-box;
        overflow: hidden;
        ::v-deep * {
          width: 100% !important;
        }
      }
    }
    .recommend {
      background: #fff;
      .van-divider {
        padding-top: 15px;
        color: inherit;
        font-size: 15px;
      }
      .recPage {
        width: 100%;
        padding: 20px;
        padding-top: 0;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        .recItem {
          font-size: 12px;
          width: 30%;
          margin-bottom: 10px;
          .img {
            width: 100%;
            height: 0;
            padding-bottom: 100%;
            position: relative;
            overflow: hidden;
            border-radius: 5px;
            img {
              width: 100%;
              height: 100%;
              position: absolute;
              top: 0;
              left: 0;
              object-fit: cover;
            }
          }
          .title {
            width: 100%;
            margin-top: 3px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
          .price {
            font-weight: bold;
            color: #24c1bb;
          }
        }
      }
    }
  }
  .bottom {
    .van-goods-action {
      padding: 2px 5px;
      .van-button {
        &.van-goods-action-button--first {
          background: linear-gradient(to right, #3cd0cb, #32deb2);
        }
        &.van-goods-action-button--last {
          background: linear-gradient(to right, #25c9c3, #168480);
        }
      }
    }
    .van-sku-container {
      ::v-deep .van-sku-header {
        .van-sku__goods-price,
        .van-sku__stock-num {
          color: #24c1bb;
        }
      }
      ::v-deep .van-sku-body {
        .van-sku-row__item--active {
          color: #24c1bb;
        }
      }
      ::v-deep .van-sku-actions .van-button {
        &:first-of-type {
          background: linear-gradient(to right, #3cd0cb, #32deb2);
        }
        &:last-of-type {
          background: linear-gradient(to right, #25c9c3, #168480);
        }
      }
    }
  }
}
</style>